<template>
  <el-container>
    <div style="padding: 10px;padding-bottom: 0">
      <div class="report_header" ref="headerHeight">
        <div style="display: flex;align-items: center">
          <div class="report_header_left"></div>
          <div style="width: 800px;display: flex;align-items: center;">
            <div class="report_header_date">
              <el-date-picker
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="report_header_query">
              <el-select  v-model="sysMchName"   placeholder="请选择商户" filterable
                         value-key="id" :filter-method="querySysmch" clearable @change="changeSysMch">
                <el-option style="width:300px" v-for="item in mchIdOptions" :key="item.id" :label="item.name" :value="item">
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="sysClick">搜索商户</div>
                </div>
                <div style="height: 40px"></div>
              </el-select>
            </div>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">

            <el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary"
                       @click="queryClick">查询
            </el-button>
          </div>
        </div>
        <div style="width: 800px;display: flex;align-items: center;" v-show="queryType == true">
          <!--          这是放隐藏条件的容器-->
        </div>
      </div>
    </div>
    <div class="pd10">
      <el-tabs type="border-card" @tab-click="tabsClick" :style="{height:curHeight+'px'}">
        <el-tab-pane label="未结算账单">
          <div class="details_card" v-loadMore="[payLoads,'order-list1']" :style="{height:tabsHeight+'px'}">
            <orderList :orderForm="orderForm" @detailsClick="detailsClick" type="1"></orderList>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已结算账单">
          <div class="details_card" v-loadMore="[payLoads,'order-list2']" :style="{height:tabsHeight+'px'}">
            <orderList :orderForm="orderForm" @detailsClick="detailsClick" type="1"></orderList>
          </div>
        </el-tab-pane>
        <el-tab-pane label="提现账单">
          <div class="details_card" v-loadMore="[payLoads,'order-list3']" :style="{height:tabsHeight+'px'}">
            <orderList :orderForm="orderForm" @detailsClick="detailsClick" type="2"></orderList>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog
    title="打款"
    :visible.sync="paymentVisible"
    v-el-drag-dialog
    append-to-body
    width="650px"
    :before-close="paymentClose">
      <div>
        <span  style="font-size: 15px;font-weight: bold">收账人名：{{paymentInfo.enterprise.bankName}}</span>
        <p  style="font-size: 15px;font-weight: bold">收账卡号：{{paymentInfo.enterprise.bankNum}}</p>
        <p  style="font-size: 15px;font-weight: bold">开户银行：{{paymentInfo.enterprise.bank}}</p>
        <div style="display: flex;align-items: center">
          <span style="font-size: 15px;font-weight: bold">提现金额：</span>
          <el-input v-model="amount" type="number" style="width: 200px"/>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px">
          <span style="font-size: 15px;font-weight: bold">付款凭证：</span>
          <el-input v-model="tranSn" type="number" style="width: 200px"/>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="paymentVisible = false">取 消</el-button>
    <el-button type="primary" @click="paymentClick">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="双击选择商户"
      :visible.sync="mchTableVisible"
      width="650px"
      v-el-drag-dialog
      append-to-body
      :before-close="mchTableClose">
      <div style="position: relative;">
        <enterprise @mchDouble="mchDouble"></enterprise>
      </div>
    </el-dialog>
    <el-footer class="el-footerBox" style="margin-bottom: auto">
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="paginationClick"></pagination>
    </el-footer>
  </el-container>
</template>

<script>
  import {enterpriseDeposit,find,transfer} from '@/api/enterpriseDeposit'
  import enterprise from '@/components/Enterprise/index'
  import {find as findBank} from '@/api/bank'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import memberTable from '@/components/MemberTable/index'
  import productTable from '@/components/ProductList/productList'
  import { EventBus } from '@/api/eventBus'
  import orderList from './components/list'
  import { distributionVoList } from '@/api/distributionVo'
  import Pagination from '@/components/Pagination'
  import utils from '../../utils/utils.js'
  import loadMore from '@/utils/more.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import { mapGetters } from 'vuex'
  import { dateFormatter } from '@/filters'
  import { mchList} from '@/api/shop'

  export default {
    name: 'order-list',
    directives: { loadMore, permission, elDragDialog },
    activated() {
      this.payLoads = new Date().getTime()
    },
    data() {
      return {
        payLoads: '',
        orderForm: [],
        times: '',
        mchTableVisible:false,
        paymentVisible:false,
        pageNum: 1,
        memberTableVisible: false,
        memberName: '',
        productName: '',
        pageSize: 20,
        amount:'',
        total: 0,
        tranSn:'',
        curHeight: null,
        sysMchName:'',
        paymentInfo:{
          enterprise:{
            bankNum:"",
            bankName:'',
          }
        },
        enterpriseId:'',
        tabsHeight: null,
        queryTypeNum:1,
        queryType: true,
        mchType: '',
        mchIdOptions: [],
        memberIdOptions: [],
        productOptions: [],
        orderStatus: 0, // 订单状态
        query: {
          date: [],
          orderSn: '',

          memberId: '',
          phone: '',
          productId: ''
        },
        keyword: {
          date: [],
          orderSn: '',
          memberId: '',
          phone: '',
          productId: ''
        },
        pickerOptions: {//时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    components: {
      orderList, Pagination, memberTable, productTable,enterprise
    },
    computed: {
      ...mapGetters([
        'mchId'
      ])
    },
    created() {
      var _this = this
      this.loadMch('')
      this.loadOrder()
      EventBus.$on('order-add', res => { // 监听新增完毕
        // 更新列表数组
        _this.orderForm.splice(0, 0, res)
      })
      EventBus.$on('order-edit', res => { // 监听状态更新
        // 更新列表数组
        for (var i = 0; i < _this.orderForm.length; i++) {
          if (_this.orderForm[i].id == res.id) {
            _this.$set(this.orderForm, i, res)
          }
        }
      })
      EventBus.$on('order-delete', res => { // 监听订单删除
        // 更新列表数组
        /* for (var i = 0; i < _this.orderForm.length; i++) {
          if (_this.orderForm[i].id == res.id) {
            _this.orderForm.splice(i,1)
            return;
          }
        } */
        this.loadOrder()
      })
      EventBus.$on('order-view', res => { // 监听订单删除
        // 更新列表数组
        for (var i = 0; i < _this.orderForm.length; i++) {
          if (_this.orderForm[i].id == res.id) {
            _this.$set(this.orderForm, i, res)
          }
        }
      })
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      paymentClick(){
        this.$confirm('确认打款?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            transfer({
              id:this.paymentInfo.enterpriseDeposit.id,
              amount:this.amount,
              tranSn:this.tranSn,
            }).then(res=>{
              this.paymentVisible=false
              this.loadRefund()
            })
          })

      },
      paymentClose(){
        this.paymentVisible=false
      },
      paginationClick(){
        if (this.queryTypeNum == 1){
          this.loadOrder()
        }else if (this.queryTypeNum == 2){
          this.loadRefund()
        }
      },
      loadRefund(){
        var params=new URLSearchParams()
        params.append('enterpriseId',this.enterpriseId)
        params.append('type',2)
        params.append('pageNum',this.pageNum)
        params.append('pageSize',this.pageSize)
        params.append('startDate', this.keyword.date == null || this.keyword.date.length == 0 ? '' : this.keyword.date[0])
        params.append('endDate', this.keyword.date == null || this.keyword.date.length == 0 ? '' : this.keyword.date[1])
        enterpriseDeposit(params).then(res=>{

          this.orderForm = res.data.data
          this.total = res.data.total

        })
      },
      mchTableClose(){
        this.mchTableVisible=false
      },
      sysClick(){
        this.mchTableVisible=true
      },
      mchDouble(data){
        this.sysMchName=data.name
        this.enterpriseId=data.enterpriseId
        this.mchTableVisible=false

        if (this.queryTypeNum == 1){
          this.loadOrder()
        }else if (this.queryTypeNum == 2){
          this.loadRefund()
        }
      },
      changeSysMch(data){
        if (!utils.isNull(data)){
          this.sysMchName=data.name
          this.enterpriseId=data.enterpriseId

        }else{
          this.sysMchName=''
          this.enterpriseId=''
        }

      },
      querySysmch(query){
        this.loadMch(query)
      },
      loadMch(query){
        mchList({
          pageSize:100,
          name:query
        }).then(res=>{
            this.mchIdOptions=res.data.data
        })
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (_this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight
              _this.curHeight = h - 311//减去页面上固定高度height
              _this.tabsHeight = h - 381
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight
              _this.curHeight = h - 224//减去页面上固定高度height
              this.tabsHeight = h - 294
            }
          })()
        }
      },
      comeIn() {
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 224//减去页面上固定高度height
        this.tabsHeight = h - 294
      },

      loadOrder() {
        var _this = this
        let params = new URLSearchParams()
        params.append('pageNum', _this.pageNum)
        params.append('pageSize', _this.pageSize)
        params.append('status', _this.orderStatus)
        if(!utils.isNull(_this.enterpriseId)){
          params.append('enterpriseId',_this.enterpriseId)
        }
        params.append('startDate', this.keyword.date == null || this.keyword.date.length == 0 ? '' : this.keyword.date[0])
        params.append('endDate', this.keyword.date == null || this.keyword.date.length == 0 ? '' : this.keyword.date[1])
        distributionVoList(params).then(response => {
          response.data.data.forEach(item=>{
            item.status=_this.orderStatus
            item.orderDate=dateFormatter(item.orderDate)
            if( item.distributionDate){
              item.distributionDate=dateFormatter(item.distributionDate)
            }else{
              var day3 = new Date();
              day3.setTime(day3.getTime()+24*60*60*1000)
              var s3 = day3.getFullYear()+"-" + (day3.getMonth()+1) + "-" + day3.getDate();
              item.distributionDate=s3
            }

          })
          _this.orderForm = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          console.log('error!!')
        })
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight
          this.curHeight = h - 311//减去页面上固定高度height
          this.tabsHeight = h - 381
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight
          this.curHeight = h - 224//减去页面上固定高度height
          this.tabsHeight = h - 294
        }
      },

      queryClick() {
        this.keyword = this.query
        this.pageNum = 1
        if (this.queryTypeNum == 1){
          this.loadOrder()
        }else if (this.queryTypeNum == 2){
          this.loadRefund()
        }


      },
      resetClick() {
        this.query.date = []
        this.query.orderSn = ''
        this.productName = ''
        this.memberName = ''
        this.query.memberId = ''
        this.query.phone = ''
        this.query.productId = ''
        this.keyword = this.query
        this.pageNum = 1
        this.loadOrder()
      },
      detailsClick(data,date,type,distributionDate) {

        if (type==1){
          this.$router.push({
            path: '/distributionVo/view', query: {
              id: data,
              date:date,
              status:this.orderStatus,
              distributionDate:this.orderStatus?distributionDate:'' }
          })
        }else{
          this.findReport(data)
        }

      },
      findReport(data){
        find(data).then(res=>{
          this.paymentInfo=res.data
          this.amount=res.data.enterpriseDeposit.debit
          findBank(this.paymentInfo.enterprise.bankId).then(response=>{
            this.paymentInfo.enterprise.bank=response.data.bankInfo.name
            this.paymentVisible=true
          })
        })
      },
      tabsClick(data) {
        var _this = this
        this.pageNum=1
        switch (data.paneName) {
          case '0':
            _this.queryTypeNum=1
            _this.orderStatus = 0 // 订单状态
            this.loadOrder()
            break
          case '1':
            _this.queryTypeNum=1
            _this.orderStatus = 1
            this.loadOrder()
            break
          case '2':
            _this.queryTypeNum=2
            this.loadRefund()
            break
        }
        console.log(_this.orderStatus)
      }
    }
  }
</script>

<style scoped>
  .details_card {
    overflow: auto;
    padding-left: 20px;
    padding-right: 20px;
    box-sizing: border-box;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
  }

  .elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }

  .details_card:hover {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
  }

  .el-input__inner {
    width: 100% !important;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/ .el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
    flex-direction: column;
  }
  /deep/.el-dialog__header{
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }
  .report_header_left {
    width: 5px;
    height: 46px;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }

  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
